// +build embfs

package views

import (
	"embed"
	"io/fs"
	"net/http"
	"path"
	"strings"

	"github.com/gin-gonic/gin"
)

//go:embed dist
var viewsFS embed.FS

func Static(r *gin.Engine, root string) {
	fs, _ := fs.Sub(viewsFS, "dist")
	emfs := http.FileServer(http.FS(fs))
	rootlen := len(root)
	r.NoRoute(func(c *gin.Context) {
		if !strings.HasPrefix(c.Request.URL.Path, root) {
			return
		}
		p := path.Clean(c.Request.URL.Path)
		if p != root {
			f, err := fs.Open(p[rootlen+1:])
			if err != nil {
				return
			}
			f.Close()
		}
		c.Request.URL.Path = c.Request.URL.Path[rootlen:]
		emfs.ServeHTTP(c.Writer, c.Request)
	})
}
